"""
自定义异常类模块

定义了XCQuant框架中使用的所有自定义异常类
"""

import traceback
from typing import Dict, Any, Optional, List
from datetime import datetime


class XCQuantError(Exception):
    """XCQuant框架基础异常类"""
    
    def __init__(self, message: str, error_code: str = None, context: Dict[str, Any] = None):
        self.message = message
        self.error_code = error_code or self.__class__.__name__
        self.context = context or {}
        self.timestamp = datetime.now()
        self.traceback_info = traceback.format_exc()
        super().__init__(message)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'error_type': self.__class__.__name__,
            'error_code': self.error_code,
            'message': self.message,
            'context': self.context,
            'timestamp': self.timestamp.isoformat(),
            'traceback': self.traceback_info
        }
    
    def get_recovery_suggestions(self) -> List[str]:
        """获取恢复建议"""
        return [
            "检查系统日志获取更多详细信息",
            "确认系统配置是否正确",
            "如果问题持续，请联系技术支持"
        ]


class ExchangeAPIError(XCQuantError):
    """交易所API调用错误"""
    def __init__(self, message: str, exchange: str = None, error_code: str = None, 
                 api_endpoint: str = None, http_status: int = None):
        self.exchange = exchange
        self.api_endpoint = api_endpoint
        self.http_status = http_status
        context = {
            'exchange': exchange,
            'api_endpoint': api_endpoint,
            'http_status': http_status
        }
        super().__init__(message, error_code, context)
    
    def get_recovery_suggestions(self) -> List[str]:
        suggestions = [
            "检查网络连接是否正常",
            "验证API密钥和权限设置",
            "检查交易所API状态和限制"
        ]
        
        if self.http_status == 429:
            suggestions.append("等待一段时间后重试，可能触发了频率限制")
        elif self.http_status == 401:
            suggestions.append("检查API密钥是否正确和有效")
        elif self.http_status >= 500:
            suggestions.append("交易所服务器可能出现问题，稍后重试")
            
        return suggestions


class DataMissingError(XCQuantError):
    """数据缺失错误"""
    def __init__(self, message: str, symbol: str = None, period: str = None, 
                 date_range: str = None):
        self.symbol = symbol
        self.period = period
        self.date_range = date_range
        context = {
            'symbol': symbol,
            'period': period,
            'date_range': date_range
        }
        super().__init__(message, context=context)
    
    def get_recovery_suggestions(self) -> List[str]:
        return [
            "尝试重新下载缺失的数据",
            "检查数据源是否可用",
            "考虑使用其他时间周期的数据",
            "验证交易对符号是否正确"
        ]


class StrategyError(XCQuantError):
    """策略执行错误"""
    def __init__(self, message: str, strategy_name: str = None, strategy_state: str = None):
        self.strategy_name = strategy_name
        self.strategy_state = strategy_state
        context = {
            'strategy_name': strategy_name,
            'strategy_state': strategy_state
        }
        super().__init__(message, context=context)
    
    def get_recovery_suggestions(self) -> List[str]:
        return [
            "检查策略参数配置",
            "验证市场数据是否完整",
            "检查账户余额和权限",
            "考虑重启策略或调整参数"
        ]


class RiskControlError(XCQuantError):
    """风险控制触发错误"""
    def __init__(self, message: str, risk_type: str = None, risk_level: str = None, 
                 triggered_rules: List[str] = None):
        self.risk_type = risk_type
        self.risk_level = risk_level
        self.triggered_rules = triggered_rules or []
        context = {
            'risk_type': risk_type,
            'risk_level': risk_level,
            'triggered_rules': triggered_rules
        }
        super().__init__(message, context=context)
    
    def get_recovery_suggestions(self) -> List[str]:
        suggestions = [
            "检查当前仓位和风险敞口",
            "调整风险控制参数",
            "等待市场条件改善"
        ]
        
        if self.risk_level == "critical":
            suggestions.insert(0, "立即停止所有交易活动")
            suggestions.append("联系风险管理团队")
            
        return suggestions


class ConfigError(XCQuantError):
    """配置错误"""
    def __init__(self, message: str, config_key: str = None):
        self.config_key = config_key
        super().__init__(message)


class OrderError(XCQuantError):
    """订单相关错误"""
    def __init__(self, message: str, order_id: str = None):
        self.order_id = order_id
        super().__init__(message)


class AccountError(XCQuantError):
    """账户相关错误"""
    def __init__(self, message: str, account_type: str = None):
        self.account_type = account_type
        super().__init__(message)


class NetworkError(XCQuantError):
    """网络连接错误"""
    def __init__(self, message: str, url: str = None):
        self.url = url
        super().__init__(message)


class ValidationError(XCQuantError):
    """数据验证错误"""
    pass


class DependencyError(XCQuantError):
    """依赖注入错误"""
    pass


class SecurityError(XCQuantError):
    """安全相关错误"""
    pass


class ServiceError(XCQuantError):
    """服务相关错误"""
    pass


class BacktestError(XCQuantError):
    """回测错误"""
    def __init__(self, message: str, backtest_id: str = None):
        self.backtest_id = backtest_id
        super().__init__(message)


class MonitoringError(XCQuantError):
    """监控系统错误"""
    def __init__(self, message: str, monitor_type: str = None):
        self.monitor_type = monitor_type
        super().__init__(message)


class ModuleError(XCQuantError):
    """模块相关错误"""
    def __init__(self, message: str, module_name: str = None):
        self.module_name = module_name
        super().__init__(message)


class PluginError(XCQuantError):
    """插件相关错误"""
    def __init__(self, message: str, plugin_name: str = None):
        self.plugin_name = plugin_name
        super().__init__(message)


class ComponentError(XCQuantError):
    """组件相关错误"""
    def __init__(self, message: str, component_name: str = None):
        self.component_name = component_name
        super().__init__(message)